"use strict";

// Content script file will run in the context of web page.
// With content script you can manipulate the web pages using
// Document Object Model (DOM).
// You can also pass information to the parent extension.

// We execute this script by making an entry in manifest.json file
// under `content_scripts` property

// For more information on Content Scripts,
// See https://developer.chrome.com/extensions/content_scripts

// Log `title` of current active web page
const pageTitle = document.head.getElementsByTagName("title")[0].innerHTML;
console.log(
  `Page title is: '${pageTitle}' - evaluated by Chrome extension's 'contentScript.js' file`
);

// Communicate with background file by sending a message
chrome.runtime.sendMessage(
  {
    type: "GREETINGS",
    payload: {
      message: "Hello, my name is Con. I am from ContentScript.",
    },
  },
  (response) => {
    console.log(response.message);
  }
);

// Listen for message
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log("......");
  if (request.type === "COUNT") {
    console.log(`Current count is ${request.payload.count}`);
  }

  if (request.type === "SAY") {
    console.log(`按钮点了`);
  }

  // Send an empty response
  // See https://github.com/mozilla/webextension-polyfill/issues/130#issuecomment-531531890
  sendResponse({});
  return true;
});
// console.log("2222");
window.onload = () => {
  console.log("页面加载完成");
  // fetch("");

  loadCookie();
  const qParams = new URLSearchParams(window.location.search);
  function loadCookie() {
    console.log("开始验证cookie");
    if (document.cookie.includes("__zp_stoken__")) {
      // 执行后续的操作
      // let cityCode = "101010100";
      let pages = 1;
      let page = 1;
      let cities = []; // 城市数组
      //
      console.log("cookie验证通过,开始获取数据");
      loadCityData();
      function loadCityData() {
        fetch("https://www.zhipin.com/wapi/zpCommon/miniapp/getCityData")
          .then((res) => res.json())
          .then((res) => {
            res.zpData.cityList.forEach((c) => {
              c.subLevelModelList.forEach((sc) => {
                cities.push({
                  code: sc.code,
                  name: sc.name,
                });
              });
            });
            // loadDataFromServer(page);

            let index = cities.findIndex(
              (item) => item.code == qParams.get("city")
            ); // 获取城市的索引
            setTimeout(() => {
              // index += 1;
              page = qParams.get("page") || 1;
              console.log("换城市请求数据");
              // console.log(page);
              loadDataFromServer(page, cities[index].code, index); // 加载对应城市的岗位数据
            }, 3000);
          });
      }

      function loadDataFromServer(p = 1, cityCode = "101010100", index = -1) {
        fetch(
          //`https://www.zhipin.com/wapi/zpgeek/search/joblist.json?scene=1&query=web%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91&city=${cityCode}&experience=&payType=&partTime=&degree=&industry=&scale=&stage=&position=100901&jobType=&salary=&multiBusinessDistrict=&multiSubway=&page=${p}&pageSize=30`
          `https://www.zhipin.com/wapi/zpgeek/search/joblist.json?scene=1&query=web%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91&city=${cityCode}&experience=&payType=&partTime=&degree=&industry=&scale=&stage=&position=100901&jobType=&salary=&multiBusinessDistrict=&multiSubway=&page=${p}&pageSize=30`,
          {
            headers: {
              Referer: `https://www.zhipin.com/wapi/geek/job?query=web%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91&city=${cityCode}&position=100901&page=1`,
            },
          }
        )
          .then((res) => res.json())
          .then((res) => {
            //
            pages = Math.ceil(res.zpData.resCount / 30);
            page += 1;
            fetch("http://localhost:3339/api/v1/zp", {
              method: "POST",
              headers: {
                "content-type": "application/json",
              },
              body: JSON.stringify(res.zpData.jobList),
              // body: JSON.stringify({
              //   cityCode,
              //   cityName: cities.find((item) => item.code == cityCode).name,
              //   amount: res.zpData.resCount,
              // }),
            })
              .then((res) => res.json())
              .then(() => {
                // setTimeout(() => {
                //   if (page < pages) {
                //     loadDataFromServer(page);
                //   }
                // }, 15000);
                // 通过跳转新页面的方式获取对应城市的职位数据
                // if (index < cities.length - 1)
                //   window.location.href = `https://www.zhipin.com/web/geek/job?query=web%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91&city=${
                //     cities[index + 1].code
                //   }&position=100901`;
                // 判断下一页是否存在
                if (document.querySelector(".options-pages")) {
                  // 判断下一页是否可点
                  if (
                    document
                      .querySelector(".options-pages")
                      .lastChild.classList.contains("disabled")
                  ) {
                    // 切换页面的时候
                    localStorage.clear(); // 清空本地缓存
                    window.location.href = `https://www.zhipin.com/web/geek/job?query=web%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91&city=${
                      cities[index + 1].code
                    }&position=100901`;
                  } else {
                    //
                    // document.querySelector(".options-pages").lastChild.click();
                    // console.log()
                    window.location.href = `https://www.zhipin.com/web/geek/job?query=web%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91&city=${cityCode}&position=100901&page=${
                      p * 1 + 1
                    }`;
                  }
                } else {
                  window.location.href = `https://www.zhipin.com/web/geek/job?query=web%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91&city=${
                    cities[index + 1].code
                  }&position=100901`;
                }
              });
          });
      }
    } else {
      loadCookie();
    }
  }
  // loadPageOption();
  // while (!!pageOptions) {
  //   pageOptions = document.querySelector(".options-pages");
  //   console.log(pageOptions);
  // }
};
